package com.example.controller;

import com.example.model.Announcement;
import com.example.service.AnnouncementService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 公告控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/announcements")
@Tag(name = "公告管理", description = "公告相关接口")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    @PostMapping
    @Operation(summary = "创建公告")
    public ResponseEntity<Map<String, Object>> createAnnouncement(
            @RequestBody Announcement announcement,
            Authentication authentication) {
        
        try {
            // 设置发布者信息
            announcement.setPublisherId(authentication.getName());
            announcement.setPublisherName(authentication.getName());

            Announcement savedAnnouncement = announcementService.createAnnouncement(announcement);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "公告创建成功");
            response.put("data", savedAnnouncement);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("创建公告失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建公告失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新公告")
    public ResponseEntity<Map<String, Object>> updateAnnouncement(
            @PathVariable Long id,
            @RequestBody Announcement announcement) {
        
        try {
            Announcement updatedAnnouncement = announcementService.updateAnnouncement(id, announcement);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "公告更新成功");
            response.put("data", updatedAnnouncement);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("更新公告失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新公告失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/{id}/publish")
    @Operation(summary = "发布公告")
    public ResponseEntity<Map<String, Object>> publishAnnouncement(@PathVariable Long id) {
        try {
            announcementService.publishAnnouncement(id);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "公告发布成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("发布公告失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "发布公告失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/{id}/cancel")
    @Operation(summary = "取消发布公告")
    public ResponseEntity<Map<String, Object>> cancelAnnouncement(@PathVariable Long id) {
        try {
            announcementService.cancelAnnouncement(id);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "取消发布成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("取消发布公告失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "取消发布公告失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除公告")
    public ResponseEntity<Map<String, Object>> deleteAnnouncement(@PathVariable Long id) {
        try {
            announcementService.deleteAnnouncement(id);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "公告删除成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("删除公告失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除公告失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取公告详情")
    public ResponseEntity<Map<String, Object>> getAnnouncementById(@PathVariable Long id) {
        try {
            Optional<Announcement> announcementOpt = announcementService.getAnnouncementByIdAndIncrementReadCount(id);
            
            Map<String, Object> response = new HashMap<>();
            if (announcementOpt.isPresent()) {
                response.put("success", true);
                response.put("data", announcementOpt.get());
            } else {
                response.put("success", false);
                response.put("message", "公告不存在");
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取公告详情失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取公告详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping
    @Operation(summary = "获取公告列表")
    public ResponseEntity<Map<String, Object>> getAnnouncements(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String targetType) {
        
        try {
            Page<Announcement> announcements;
            
            if (targetType != null && !targetType.isEmpty()) {
                Announcement.TargetType target = Announcement.TargetType.valueOf(targetType.toUpperCase());
                announcements = announcementService.getAnnouncementsByTargetType(target, page, size);
            } else {
                announcements = announcementService.getPublishedAnnouncements(page, size);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", announcements);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取公告列表失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取公告列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/valid")
    @Operation(summary = "获取有效公告")
    public ResponseEntity<Map<String, Object>> getValidAnnouncements(
            @RequestParam(required = false) String targetType) {
        
        try {
            List<Announcement> announcements;
            
            if (targetType != null && !targetType.isEmpty()) {
                Announcement.TargetType target = Announcement.TargetType.valueOf(targetType.toUpperCase());
                announcements = announcementService.getValidAnnouncementsByTargetType(target);
            } else {
                announcements = announcementService.getValidAnnouncements();
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", announcements);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取有效公告失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取有效公告失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/pinned")
    @Operation(summary = "获取置顶公告")
    public ResponseEntity<Map<String, Object>> getPinnedAnnouncements() {
        try {
            List<Announcement> announcements = announcementService.getPinnedAnnouncements();

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", announcements);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取置顶公告失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取置顶公告失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/search")
    @Operation(summary = "搜索公告")
    public ResponseEntity<Map<String, Object>> searchAnnouncements(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            Page<Announcement> announcements = announcementService.searchAnnouncements(keyword, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", announcements);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("搜索公告失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "搜索公告失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取公告统计信息")
    public ResponseEntity<Map<String, Object>> getAnnouncementStatistics() {
        try {
            Map<String, Object> statistics = announcementService.getAnnouncementStatistics();

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", statistics);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取公告统计信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取公告统计信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
